﻿<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>晃动的图片</title>
    <script language="JavaScript">
        step = 0;
        obj = new Image();        //创建图片对象
        function anim(xp,xk,smer) //smer 代表晃动方向
        {
            obj.style.left = x;
            x += step*smer;
            if (x>=(xk+xp)/2) {
                if (smer == 1) step--; //往左移动
                else step++;
            }
            else {
                if (smer == 1) step++; //往右移动
                else step--;
            }

            if (x >= xk) {      //如果已经到右边界，则反向晃动
                x = xk;
                smer = -1;
            }

            if (x <= xp) {   //如果一定到左边界，则反向晃动
                x = xp;
                smer = 1;
            }
            setTimeout('anim('+xp+','+xk+','+smer+')', 40); //设置定时器，实现不断晃动效果
        }

        function moveLR(objID,movingarea_width,c)
        {

            if (navigator.appName=="Netscape") window_width = window.innerWidth;
            else window_width = document.body.offsetWidth;   //获取窗体的宽度
            obj = document.images[objID];
            image_width = obj.width;                            //获取图像的宽度

            x1 = obj.style.left;                                //获取图像的X坐标
            x = Number(x1.substring(0,x1.length-2));            //去掉后面的像素标记“px”
            if (c == 0) {
                if (movingarea_width == 0) {                  //没有设置移动区域的情况
                    right_margin = window_width - image_width;
                    anim(x,right_margin,1);                  //开始晃动图片
                }
                else {
                    right_margin = x + movingarea_width - image_width;
                    if (movingarea_width < x + image_width) window.alert("No space for moving!");
                    else anim(x,right_margin,1);
                }
            }
            else {
                if (movingarea_width == 0)                                                     //没有设置移动区域的情况
                    right_margin = window_width - image_width;
                else {
                    x = Math.round((window_width-movingarea_width)/2);
                    right_margin = Math.round((window_width+movingarea_width)/2)-image_width;//获取可以移动的空间
                }
                anim(x,right_margin,1);
            }
        }
    </script>
    <img src="http://www.baidu.com/img/logo.gif" name="img1" style='position: absolute; top: 50px; left: 213px;' border=0 id="myImg">
    <script language="JavaScript">
        setTimeout("moveLR('myImg',400,1)",10);
    </script>
</head>
<body>

</body>
</html>